package com.yhsoft.benefitcard.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhsoft.benefitcard.controller.request.*;
import com.yhsoft.benefitcard.controller.response.*;
import com.yhsoft.benefitcard.entity.BatchGoods;
import com.yhsoft.benefitcard.entity.CardsBatch1;
import com.yhsoft.benefitcard.entity.CardsBatch2;
import com.yhsoft.benefitcard.entity.CardsInfo;
import com.yhsoft.benefitcard.service.IBatchGoodsService;
import com.yhsoft.benefitcard.service.ICardsBatch1Service;
import com.yhsoft.benefitcard.service.ICardsBatch2Service;
import com.yhsoft.benefitcard.service.ICardsInfoService;
import com.yhsoft.bill.service.ISalerYszkMxService;
import com.yhsoft.bill.service.ISalerYszkService;
import com.yhsoft.buyer.controller.request.VenderOrdersInVo;
import com.yhsoft.buyer.controller.response.OrdersDyOutVo;
import com.yhsoft.buyer.controller.response.VenderOrdersOutVo;
import com.yhsoft.buyer.service.IBuyerOrderService;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.utils.DateUtils;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.common.vo.Result;
import com.yhsoft.goods.service.IGoodsInfoService;
import com.yhsoft.mall.entity.TopicInfo;
import com.yhsoft.mall.service.ITopicInfoService;
import com.yhsoft.sys.entity.CustomerInfo;
import com.yhsoft.sys.service.ICustomerInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 福利卡信息表 前端控制器
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-10-04
 */
@Api(tags = {"D-福利卡接口列表"})
@RestController
@RequestMapping("/benefitcard")
public class CardsInfoController {
    @Resource
    private ICardsInfoService iCardsInfoService;

    @Resource
    private ICardsBatch1Service iCardsBatch1Service;

    @Resource
    private ICardsBatch2Service iCardsBatch2Service;

    @Resource
    private IGoodsInfoService goodsInfoService;

    @Resource
    private IBatchGoodsService iBatchGoodsService;

    @Resource
    private ISalerYszkMxService iSalerYszkMxService;

    @Resource
    private ISalerYszkService iSalerYszkService;

    @Resource
    private ICustomerInfoService iCustomerInfoService;

    @Resource
    private ITopicInfoService iTopicInfoService;

    @Resource
    private IBuyerOrderService iBuyerOrderService;

    @ApiOperation("新增福利卡批次/备卡")
    @PostMapping("/addCardsBatch1")
    public Result<?> addCardsBatch1(@RequestBody AddCardsBatch1InVo inVo) {
        // CardType: JFK 积分卡 DYQ 电影券  LPK 礼品卡
        String batchNum = IDGenerator.generate12(inVo.getCardType());
        iCardsBatch1Service.addBatch1(inVo, batchNum);
        iCardsInfoService.addCardsInfo(inVo, batchNum);
        return Result.success("新增成功！");
    }

    @ApiOperation("卡券激活")
    @PostMapping("/addCardsBatch2")
    public Result<?> addCardsBatch2(@RequestBody AddCardBatch2InVo inVo) {
        // CardType: JFK 积分卡 DYQ 电影券  LPK 礼品卡
        // 获取号段
        CardsBatch1 batch1 = iCardsBatch1Service.getById(inVo.getBatch1Id());
        // 判断可激活张数是否充足
        Integer num = batch1.getActivatedNum();
        Integer num2 = num + Integer.parseInt(inVo.getActivateNum());
        if (num2 > batch1.getTotalNum()) {
            return Result.fail("激活失败！该批次内的可激活张数不足，请重新备卡。");
        }

        // 建立激活批次
        String firstBatchNum = batch1.getFirstBatchNum();
        String secondBantchNum = IDGenerator.generate12(inVo.getCardType());
        iCardsBatch2Service.addBatch2(inVo, firstBatchNum, secondBantchNum, num);

        // 更新福利卡信息
        QueryWrapper<CardsInfo> wrapper = new QueryWrapper<>();
        wrapper.select("id").eq("first_batch_num", firstBatchNum)
                .eq("is_activated", 0)
                .orderByAsc("id")
                .last("limit 0," + Integer.parseInt(inVo.getActivateNum()) + "");
        List<CardsInfo> cardsInfos = iCardsInfoService.getBaseMapper().selectList(wrapper);

        cardsInfos.forEach(e -> {
            e.setBalance(new BigDecimal(inVo.getFaceValue()));
            e.setIsActivated(1);
            e.setSecondBantchNum(secondBantchNum);
            e.setActivationTime(LocalDateTime.now());
        });

        iCardsInfoService.updateBatchById(cardsInfos, Integer.parseInt(inVo.getActivateNum()));

        // 设置第一批次已激活数量
        batch1.setActivatedNum(num2);
        // 设置总收入
        BigDecimal oldTotal = batch1.getTotalIncome();
        BigDecimal sum = new BigDecimal(inVo.getActivateNum());
        BigDecimal price = new BigDecimal(inVo.getFaceValue());
        BigDecimal total = sum.multiply(price).add(oldTotal);
        batch1.setTotalIncome(total);

        // 设置结算成本
        BigDecimal oldCost = batch1.getCost();
        BigDecimal priceCost = new BigDecimal(inVo.getSalePrice());
        BigDecimal totalCost = sum.multiply(priceCost).add(oldCost);
        batch1.setCost(totalCost);

        // 设置毛利
        BigDecimal profit = total.subtract(totalCost);
        batch1.setProfit(profit);
        iCardsBatch1Service.updateById(batch1);

        // 更新应收表
        iSalerYszkService.updateYszk(inVo.getCustomerId(), sum.multiply(price));

        iSalerYszkMxService.addYfmx(inVo.getCustomerId(), sum.multiply(price), firstBatchNum, secondBantchNum);
        return Result.success("激活成功！批次号:" + secondBantchNum);
    }

    @ApiOperation("为此批次新增卡券")
    @PostMapping("/updateCardsBatch2")
    public Result<?> updateCardsBatch2(@RequestBody UpdateCardsBatch2InVo inVo) {
        CardsBatch2 batch2 = iCardsBatch2Service.getById(inVo.getBatch2Id());
        if (batch2 == null) {
            return Result.fail("批次不存在");
        }

        // 判断可激活张数是否充足
        LambdaQueryWrapper<CardsBatch1> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(CardsBatch1::getFirstBatchNum, batch2.getFirstBatchNum());
        CardsBatch1 batch1 = iCardsBatch1Service.getBaseMapper().selectOne(wrapper);

        Integer num = batch1.getActivatedNum();
        Integer num2 = num + Integer.parseInt(inVo.getActivateNum());
        if (num2 > batch1.getTotalNum()) {
            return Result.fail("激活失败！该批次内的可激活张数不足，请重新备卡。");
        }

        // 更新号段
        StringBuilder pNum = new StringBuilder(batch2.getParagraphNumber());
        num = num + 1;
        pNum.append("," + num + "~" + num2);
        batch2.setParagraphNumber(pNum.toString());
        iCardsBatch2Service.updateById(batch2);

        // 更新福利卡信息
        String firstBatchNum = batch1.getFirstBatchNum();
        String secondBantchNum = batch2.getSecondBantchNum();
        QueryWrapper<CardsInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.select("id").eq("first_batch_num", firstBatchNum)
                .eq("is_activated", 0)
                .orderByAsc("id")
                .last("limit 0," + Integer.parseInt(inVo.getActivateNum()) + "");
        List<CardsInfo> cardsInfos = iCardsInfoService.getBaseMapper().selectList(wrapper1);

        cardsInfos.forEach(e -> {
            e.setBalance(new BigDecimal(batch2.getFaceValue()));
            e.setIsActivated(1);
            e.setSecondBantchNum(secondBantchNum);
            e.setActivationTime(LocalDateTime.now());
        });

        iCardsInfoService.updateBatchById(cardsInfos, Integer.parseInt(inVo.getActivateNum()));

        // 设置第一批次已激活数量
        batch1.setActivatedNum(num2);
        // 设置总收入
        BigDecimal oldTotal = batch1.getTotalIncome();
        BigDecimal sum = new BigDecimal(inVo.getActivateNum());
        BigDecimal price = new BigDecimal(batch2.getFaceValue());
        BigDecimal total = sum.multiply(price).add(oldTotal);
        batch1.setTotalIncome(total);

        // 设置结算成本
        BigDecimal oldCost = batch1.getCost();
        BigDecimal priceCost = new BigDecimal(batch2.getSalePrice());
        BigDecimal totalCost = sum.multiply(priceCost).add(oldCost);
        batch1.setCost(totalCost);

        // 设置毛利
        BigDecimal profit = total.subtract(totalCost);
        batch1.setProfit(profit);
        iCardsBatch1Service.updateById(batch1);

        // 统计
        LambdaQueryWrapper<CardsInfo> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(CardsInfo::getSecondBantchNum, batch2.getSecondBantchNum());
        long count = iCardsInfoService.count(wrapper2);
        return Result.success("新增号段 " + num + "~" + num2 + "，共计 " + count + " 张。");
    }

    @ApiOperation("获取渠道商商品清单")
    @GetMapping("/getNotSelectedGoodsList")
    public Result<PageResult<GetGoodsListOutVo>> getNotSelectedGoodsList(GetGoodsListInVo inVo,
                                                                         @RequestParam(value = "pageNo") Long pageNo,
                                                                         @RequestParam(value = "pageSize") Long pageSize) {
        IPage<GetGoodsListOutVo> iPage = goodsInfoService.getNotSelectedGoodsList(inVo, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("关联积分卡可用商品")
    @PostMapping("/addJFKGoods")
    public Result<?> addJFKGoods(@RequestBody AddJFKGoodsInVo inVo) {
        if (!StringUtils.hasLength(inVo.getSecondBantchNum()) || inVo.getGoodsIds().size() == 0) {
            return Result.success("输入非法！");
        }

        LambdaQueryWrapper<BatchGoods> wrapper = new LambdaQueryWrapper<>();
        for (Integer a : inVo.getGoodsIds()) {
            BatchGoods batchGoods = new BatchGoods();
            batchGoods.setGoodsId(a);
            batchGoods.setSecondBantchNum(inVo.getSecondBantchNum());
            batchGoods.setAddPrice(inVo.getAddPrice());

            wrapper.clear();
            wrapper.eq(BatchGoods::getSecondBantchNum, inVo.getSecondBantchNum());
            wrapper.eq(BatchGoods::getGoodsId, a);
            iBatchGoodsService.saveOrUpdate(batchGoods, wrapper);
        }
        return Result.success("新增成功！");
    }

    @ApiOperation("删除积分卡可用商品")
    @PostMapping("/delJFKGoods")
    public Result<?> delJFKGoods(@RequestBody DelJFKGoodsInVo inVo) {
        if (!StringUtils.hasLength(inVo.getSecondBantchNum()) || inVo.getGoodsIds().size() == 0) {
            return Result.success("输入非法！");
        }

        LambdaQueryWrapper<BatchGoods> wrapper = new LambdaQueryWrapper<>();
        for (Integer a : inVo.getGoodsIds()) {
            wrapper.clear();
            wrapper.eq(BatchGoods::getSecondBantchNum, inVo.getSecondBantchNum());
            wrapper.eq(BatchGoods::getGoodsId, a);
            iBatchGoodsService.remove(wrapper);
        }

        return Result.success("删除成功！");
    }

    @ApiOperation("获取积分卡可用商品清单")
    @GetMapping("/getJFKGoodsList")
    public Result<PageResult<GetJFKGoodListOutVo>> getJFKGoodsList(GetJFKGoodListInVo inVo,
                                                                   @RequestParam(value = "batch2Num") @ApiParam(value = "激活批次号") String batch2Num,
                                                                   @RequestParam(value = "goodsType") @ApiParam(value = "商品类型：1-电影，2-蛋糕，3-电子券，4-api电商，5-线下供应商 ") Integer goodsType,
                                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                                   @RequestParam(value = "pageSize") Long pageSize) {
        IPage<GetJFKGoodListOutVo> iPage = goodsInfoService.getJFKSelectedGoodsList(inVo,
                batch2Num, goodsType, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("卡号信息详情")
    @GetMapping("/getCardDetail")
    public Result<CardsDetailOutVo> getCardDetail(@RequestParam(value = "cardNo",required = false) String cardNo) {
        CardsDetailOutVo cardsDetailOutVo = iCardsInfoService.getCardDetail(cardNo);
        return Result.success(cardsDetailOutVo);
    }

    @ApiOperation("卡券信息查询（商品订单）")
    @GetMapping("/getCardOrderList")
    public Result<PageResult<VenderOrdersOutVo>> getOrderList(@RequestParam(value = "cardNo",required = false) String cardNo,
                                                              @RequestParam(value = "pageNo") Long pageNo,
                                                              @RequestParam(value = "pageSize") Long pageSize) {
        IPage<VenderOrdersOutVo> iPage = iBuyerOrderService.getSalerOrderList_query(cardNo, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("卡券信息查询（电影订单）")
    @GetMapping("/getDYOrderList")
    public Result<PageResult<OrdersDyOutVo>> getDYOrderList(@RequestParam(value = "cardNo",required = false) String cardNo,
                                                            @RequestParam(value = "pageNo") Long pageNo,
                                                            @RequestParam(value = "pageSize") Long pageSize) {
        IPage<OrdersDyOutVo> iPage = iBuyerOrderService.getSalerOrderList_query_dy(cardNo, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("福利卡管理（获取福利卡列表）")
    @GetMapping("/getAllFLCardList")
    public Result<PageResult<CardListOutVo>> getAllFLCardList(AllFLKInVo inVo,
                                                              @RequestParam(value = "pageNo") Long pageNo,
                                                              @RequestParam(value = "pageSize") Long pageSize) {
        if(!StringUtils.hasLength(inVo.getBantchNum()) && StringUtils.hasLength(inVo.getBenefitCardsNum())){
            LambdaQueryWrapper<CardsInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CardsInfo::getBenefitCardsNum, inVo.getBenefitCardsNum());
            CardsInfo cardsInfo = iCardsInfoService.getOne(wrapper);
            if(cardsInfo == null){
                return Result.success("未查询到批次信息！");
            }else{
                inVo.setBantchNum(cardsInfo.getFirstBatchNum());
            }
        }

        LambdaQueryWrapper<CardsBatch1> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardsBatch1::getDistributorId, TokenService.getUserBytoken().getCompanyId());
        wrapper.like(StringUtils.hasLength(inVo.getBantchNum()), CardsBatch1::getFirstBatchNum, inVo.getBantchNum());
        wrapper.like(StringUtils.hasLength(inVo.getCardType()), CardsBatch1::getCardType, inVo.getCardType());
        Page<CardsBatch1> page = new Page<>(pageNo, pageSize);
        IPage<CardsBatch1> iPage = iCardsBatch1Service.page(page, wrapper);

        IPage<CardListOutVo> cardListOutVoIPage = iPage.convert(a -> {
            CardListOutVo cardListOutVo = new CardListOutVo();
            BeanUtils.copyProperties(a, cardListOutVo);
            return cardListOutVo;
        });
        return Result.success(PageResult.valueOf(cardListOutVoIPage));
    }

    @ApiOperation("查看批次详情")
    @GetMapping("/getBatch2CardList")
    public Result<PageResult<Batch2CardListOutVo>> getBatch2CardList(GetBatch2CardListInVo inVo,
                                                                     @RequestParam(value = "batch1Num") String batch1Num,
                                                                     @RequestParam(value = "pageNo") Long pageNo,
                                                                     @RequestParam(value = "pageSize") Long pageSize) {
        if(!StringUtils.hasLength(inVo.getSecondBantchNum()) && StringUtils.hasLength(inVo.getBenefitCardsNum())){
            LambdaQueryWrapper<CardsInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CardsInfo::getBenefitCardsNum, inVo.getBenefitCardsNum());
            CardsInfo cardsInfo = iCardsInfoService.getOne(wrapper);
            if(cardsInfo == null){
                return Result.success("未查询到批次信息！");
            }else{
                inVo.setSecondBantchNum(cardsInfo.getSecondBantchNum());
            }
        }

        LambdaQueryWrapper<CardsBatch2> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(CardsBatch2::getFirstBatchNum, batch1Num);
        wrapper.like(StringUtils.hasLength(inVo.getSecondBantchNum()), CardsBatch2::getSecondBantchNum,
                inVo.getSecondBantchNum());
        wrapper.like(StringUtils.hasLength(inVo.getFaceValue()), CardsBatch2::getFaceValue, inVo.getFaceValue());
        wrapper.inSql(StringUtils.hasLength(inVo.getCompanyName()), CardsBatch2::getCustomerId, "select id from " +
                "baic_customer_info where customer_name like '%%" + inVo.getCompanyName() + "%%'");

        wrapper.eq(inVo.getIsEnable() != null, CardsBatch2::getIsEnable, inVo.getIsEnable());
        wrapper.like(StringUtils.hasLength(inVo.getEnableCity()), CardsBatch2::getEnableCity, inVo.getEnableCity());
        wrapper.eq(inVo.getIsFlimFk() != null, CardsBatch2::getIsFlimFk, inVo.getIsFlimFk());
        wrapper.eq(inVo.getIsSpecialShowing() != null, CardsBatch2::getIsSpecialShowing, inVo.getIsSpecialShowing());

        wrapper.ge(inVo.getStartTime_jh() != null, CardsBatch2::getCreateTime, inVo.getStartTime_jh());
        if (inVo.getEndTime_jh() != null) {
            wrapper.le(CardsBatch2::getCreateTime, LocalDateTime.of(inVo.getEndTime_jh(), LocalTime.MAX));
        }

        wrapper.ge(inVo.getStartTime_yxq() != null, CardsBatch2::getStartTime, inVo.getStartTime_yxq());
        if (inVo.getEndTime_yxq() != null) {
            wrapper.le(CardsBatch2::getEndTime, LocalDateTime.of(inVo.getEndTime_yxq(), LocalTime.MAX));
        }

        Page<CardsBatch2> page = new Page<>(pageNo, pageSize);
        IPage<CardsBatch2> iPage = iCardsBatch2Service.page(page, wrapper);

        IPage<Batch2CardListOutVo> outVoIPage = iPage.convert(a -> {
            Batch2CardListOutVo outVo = new Batch2CardListOutVo();
            BeanUtils.copyProperties(a, outVo);
            outVo.setCompanyName(getCustomerName(a.getCustomerId()));
            // 统计
            LambdaQueryWrapper<CardsInfo> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(CardsInfo::getSecondBantchNum, outVo.getSecondBantchNum());
            long count = iCardsInfoService.count(wrapper2);
            outVo.setNum(count + "");

            // 展示专题的标题
            if (StringUtils.hasLength(a.getSalesTopicId())) {
                TopicInfo topicInfo = iTopicInfoService.getById(a.getSalesTopicId());
                if (topicInfo != null) {
                    outVo.setSalesTopicName(topicInfo.getName());
                    outVo.setSalesTopicId(topicInfo.getId());
                    outVo.setSalesTopicType(topicInfo.getType());
                }
            }

            // 有效期
            // 是否限制有效期
            if (a.getIsLimitedDate() != null && a.getIsLimitedDate() == 1) {
                outVo.setYxq(a.getStartTime() + "~" + a.getEndTime());
            } else {
                outVo.setYxq("不限制");
            }

            return outVo;
        });
        return Result.success(PageResult.valueOf(outVoIPage));
    }

    /**
     * 导出激活批次
     */
    @ApiOperation("导出激活批次")
    @GetMapping("/exportExcel")
    public void export(@RequestParam(value = "batch1Num") String batch1Num, HttpServletResponse response){
        iCardsBatch2Service.export(batch1Num,response);
    }

    /**
     * 获取下游企业名称
     *
     * @param customerId
     */
    private String getCustomerName(Integer customerId) {
        CustomerInfo customerInfo = iCustomerInfoService.getById(customerId);
        if (customerInfo == null) {
            return null;
        }
        return customerInfo.getCustomerName();
    }

    @ApiOperation("激活批次号段列表")
    @GetMapping("/getCardList")
    public Result<PageResult<CardsInfoOutVo>> getCardList(@RequestParam(value = "batch2Num") String batch2Num,
                                                          @RequestParam(value = "pageNo") Long pageNo,
                                                          @RequestParam(value = "pageSize") Long pageSize) {
        IPage<CardsInfoOutVo> iPage = iCardsInfoService.getCardList(batch2Num, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("卡号列表")
    @GetMapping("/getBatch1CardList")
    public Result<PageResult<Batch1CardListOutVo>> getBatch1CardList(@RequestParam(value = "firstBatchNum") @ApiParam(value = "批次号") String firstBatchNum,
                                                                     @RequestParam(value = "isActivated", required =
                                                                             false) @ApiParam(value = "是否被激活 0-未激活 " +
                                                                             "1-已激活") Integer isActivated,
                                                                     @RequestParam(value = "pageNo") Long pageNo,
                                                                     @RequestParam(value = "pageSize") Long pageSize) {
        IPage<Batch1CardListOutVo> iPage = iCardsInfoService.getBatch1CardList(firstBatchNum, isActivated, pageNo,
                pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("设置第二批次状态")
    @PostMapping("/setJFKStutas")
    public Result<?> setJFKStutas(@RequestBody JFKStutasInVo inVo) {
        if (inVo.getIds().size() == 0) {
            return Result.success("输入非法！");
        }
        inVo.getIds().forEach(a -> {
            CardsBatch2 cardsBatch2 = iCardsBatch2Service.getById(a);

            // 设置是否电影票风控
            if (inVo.getIsFlimFk() != null) {
                cardsBatch2.setIsFlimFk(inVo.getIsFlimFk());
            }

            // 设置是否特殊场次购票
            if (inVo.getIsSpecialShowing() != null) {
                cardsBatch2.setIsSpecialShowing(inVo.getIsSpecialShowing());
            }

            // 设置是否被冻结
            if (inVo.getIsEnable() != null) {
                cardsBatch2.setIsEnable(inVo.getIsEnable());
            }

            iCardsBatch2Service.updateById(cardsBatch2);
        });
        return Result.success("修改成功！");
    }

    @ApiOperation("设置第一批次状态")
    @PostMapping("/setBatch1Stutas")
    public Result<?> setStutas(@RequestBody Batch1StutasInVo inVo) {
        if (inVo.getIds().size() == 0) {
            return Result.success("输入非法！");
        }
        inVo.getIds().forEach(a -> {
            CardsBatch1 cardsBatch1 = iCardsBatch1Service.getById(a);

            // 设置是否被冻结
            if (inVo.getIsEnable() != null) {
                cardsBatch1.setIsEnable(inVo.getIsEnable());

                // 第一批次冻结，下属的要全部冻结
                LambdaQueryWrapper<CardsBatch2> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CardsBatch2::getFirstBatchNum, cardsBatch1.getFirstBatchNum());
                List<CardsBatch2> batch2List = iCardsBatch2Service.list(wrapper);
                batch2List.forEach(b -> {
                    b.setIsEnable(inVo.getIsEnable());
                    iCardsBatch2Service.updateById(b);
                });

            }

            iCardsBatch1Service.updateById(cardsBatch1);

        });
        return Result.success("修改成功！");
    }

    @ApiOperation("查看福利卡列表")
    @GetMapping("/getDistributorCardList")
    public Result<PageResult<Batch2CardListOutVo>> getDistributorCardList(GetCardListInVo inVo,
                                                                          @RequestParam(value = "distributorId") String distributorId,
                                                                          @RequestParam(value = "pageNo") Long pageNo,
                                                                          @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<CardsBatch2> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardsBatch2::getDistributorId, distributorId);
        // 条件查询
        wrapper.eq(StringUtils.hasLength(inVo.getCardType()), CardsBatch2::getCardType, inVo.getCardType());
        wrapper.like(StringUtils.hasLength(inVo.getBantch2Num()), CardsBatch2::getSecondBantchNum,
                inVo.getBantch2Num());
        wrapper.like(StringUtils.hasLength(inVo.getBantch1Num()), CardsBatch2::getFirstBatchNum, inVo.getBantch1Num());
        wrapper.like(StringUtils.hasLength(inVo.getFaceValue()), CardsBatch2::getFaceValue, inVo.getFaceValue());
        wrapper.eq(inVo.getIsEnable() != null, CardsBatch2::getIsEnable, inVo.getIsEnable());
        wrapper.like(StringUtils.hasLength(inVo.getEnableCity()), CardsBatch2::getEnableCity, inVo.getEnableCity());
        wrapper.eq(inVo.getIsFlimFk() != null, CardsBatch2::getIsFlimFk, inVo.getIsFlimFk());
        wrapper.eq(inVo.getIsSpecialShowing() != null, CardsBatch2::getIsSpecialShowing, inVo.getIsSpecialShowing());

        wrapper.ge(inVo.getStartTime_jh() != null, CardsBatch2::getCreateTime, inVo.getStartTime_jh());
        if (inVo.getEndTime_jh() != null) {
            wrapper.le(CardsBatch2::getCreateTime, LocalDateTime.of(inVo.getEndTime_jh(), LocalTime.MAX));
        }

        wrapper.ge(inVo.getStartTime_yxq() != null, CardsBatch2::getStartTime, inVo.getStartTime_yxq());
        if (inVo.getEndTime_yxq() != null) {
            wrapper.le(CardsBatch2::getEndTime, LocalDateTime.of(inVo.getEndTime_yxq(), LocalTime.MAX));
        }

        Page<CardsBatch2> page = new Page<>(pageNo, pageSize);
        IPage<CardsBatch2> iPage = iCardsBatch2Service.page(page, wrapper);

        IPage<Batch2CardListOutVo> outVoIPage = iPage.convert(a -> {
            Batch2CardListOutVo outVo = new Batch2CardListOutVo();
            BeanUtils.copyProperties(a, outVo);
            // 统计
            LambdaQueryWrapper<CardsInfo> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(CardsInfo::getSecondBantchNum, outVo.getSecondBantchNum());
            long count = iCardsInfoService.count(wrapper2);
            outVo.setNum(count + "");
            return outVo;
        });
        return Result.success(PageResult.valueOf(outVoIPage));
    }

    @ApiOperation("平台-渠道商管理-卡券列表")
    @PostMapping("/getDisCardList")
    public Result<PageResult<Batch2CardListOutVo>> getDisCardList(@Valid @RequestBody GetDisCardListInVo inVo) {
        LambdaQueryWrapper<CardsBatch2> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(CardsBatch2::getDistributorId, inVo.getDistributorId());
        wrapper.like(StringUtils.hasLength(inVo.getSecondBantchNum()), CardsBatch2::getSecondBantchNum,
                inVo.getSecondBantchNum());
        wrapper.like(StringUtils.hasLength(inVo.getFaceValue()), CardsBatch2::getFaceValue, inVo.getFaceValue());

        wrapper.inSql(StringUtils.hasLength(inVo.getCompanyName()), CardsBatch2::getCustomerId, "select id from " +
                "baic_customer_info where customer_name like '%%" + inVo.getCompanyName() + "%%'");

        wrapper.eq(inVo.getIsEnable() != null, CardsBatch2::getIsEnable, inVo.getIsEnable());
        wrapper.like(StringUtils.hasLength(inVo.getEnableCity()), CardsBatch2::getEnableCity, inVo.getEnableCity());
        wrapper.eq(inVo.getIsFlimFk() != null, CardsBatch2::getIsFlimFk, inVo.getIsFlimFk());
        wrapper.eq(inVo.getIsSpecialShowing() != null, CardsBatch2::getIsSpecialShowing, inVo.getIsSpecialShowing());

        wrapper.ge(inVo.getStartTime_jh() != null, CardsBatch2::getCreateTime, inVo.getStartTime_jh());
        if (inVo.getEndTime_jh() != null) {
            wrapper.le(CardsBatch2::getCreateTime, LocalDateTime.of(inVo.getEndTime_jh(), LocalTime.MAX));
        }

        wrapper.ge(inVo.getStartTime_yxq() != null, CardsBatch2::getStartTime, inVo.getStartTime_yxq());
        if (inVo.getEndTime_yxq() != null) {
            wrapper.le(CardsBatch2::getEndTime, LocalDateTime.of(inVo.getEndTime_yxq(), LocalTime.MAX));
        }

        Page<CardsBatch2> page = new Page<>(inVo.getPageNo(), inVo.getPageSize());
        IPage<CardsBatch2> iPage = iCardsBatch2Service.page(page, wrapper);

        IPage<Batch2CardListOutVo> outVoIPage = iPage.convert(a -> {
            Batch2CardListOutVo outVo = new Batch2CardListOutVo();
            BeanUtils.copyProperties(a, outVo);
            outVo.setCompanyName(getCustomerName(a.getCustomerId()));
            // 统计
            LambdaQueryWrapper<CardsInfo> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(CardsInfo::getSecondBantchNum, outVo.getSecondBantchNum());
            long count = iCardsInfoService.count(wrapper2);
            outVo.setNum(count + "");

            // 展示专题的标题
            if (StringUtils.hasLength(a.getSalesTopicId())) {
                TopicInfo topicInfo = iTopicInfoService.getById(a.getSalesTopicId());
                if (topicInfo != null) {
                    outVo.setSalesTopicName(topicInfo.getName());
                    outVo.setSalesTopicId(topicInfo.getId());
                    outVo.setSalesTopicType(topicInfo.getType());
                }
            }

            // 有效期
            // 是否限制有效期
            if (a.getIsLimitedDate() != null && a.getIsLimitedDate() == 1) {
                outVo.setYxq(a.getStartTime() + "~" + a.getEndTime());
            } else {
                outVo.setYxq("不限制");
            }

            return outVo;
        });
        return Result.success(PageResult.valueOf(outVoIPage));
    }

    @ApiOperation("激活批次使用情况")
    @GetMapping("/getCardUsage")
    public Result<CardUsageOutVo> getCardUsage(@RequestParam(value = "batch2Num") String batch2Num,
                                               @RequestParam(value = "distributorId", required = false) @ApiParam(value = "渠道商id,平台使用此接口时必传") Integer distributorId) {
        CardUsageOutVo outVo;
        outVo = iCardsInfoService.getCardUsage(batch2Num, distributorId);
        return Result.success(outVo);
    }

    @ApiOperation("设置电影券批次加价")
    @PostMapping("/setFlimBatchAddPrice")
    public Result<?> setFlimBatchAddPrice(@Valid @RequestBody SetFlimBatchAddPriceInVo inVo){
        return  Result.success(iCardsInfoService.setFlimBatchAddPrice(inVo));
    }

    @ApiOperation("用户的卡券使用情况")
    @GetMapping("/getCardUseInfo")
    public Result<PageResult<OrderCardOutVo>> getCardUseInfo(
            @RequestParam(value = "cardType",required = false) String cardType,
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize) {
        //@RequestParam(value = "distributorId") String distributorId,
        IPage<OrderCardOutVo> iPage = iCardsInfoService.getCardUseInfo(cardType,userId, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }
}
